/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Utility;
import PIServer.LocalSettings;
import PIServer.Main;
import java.util.Properties;
import net.spy.memcached.AddrUtil;
import net.spy.memcached.BinaryConnectionFactory;
import net.spy.memcached.MemcachedClient;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author nguyendn
 */
public class Memcache {

    public static Logger log = LoggerFactory.getLogger(Memcache.class.getName());

    private static final String NAMESPACE = "VIVOO-MOBILE:5d41402abc4b2a76b9719d91101";
    
    private static Memcache instance = null;
    private static MemcachedClient[] m = null;

    private Memcache() {
        configMemcache();

        try {
            m = new MemcachedClient[21];
            for (int i = 0; i <= 20; i++) {
                MemcachedClient c = new MemcachedClient(
                        new BinaryConnectionFactory(),
                        AddrUtil.getAddresses(LocalSettings.MEMCACHE_SERVER));
                m[i] = c;
            }
        } catch (Exception ex) {
            log.error(ex.getClass().getName(), ex);
        }
    }

    public static synchronized Memcache getInstance() {
        log.info("Instance: " + instance);
        if (instance == null) {
            log.info("Creating a new instance");
            instance = new Memcache();
        }
        return instance;
    }

    public void set(String key, int ttl, final Object o) {
        getCache().set(NAMESPACE + key, ttl, o);
    }

    public Object get(String key) {
        Object o = getCache().get(NAMESPACE + key);
        if (o == null) {
            log.debug("Cache MISS for KEY: " + key);
        } else {
            log.debug("Cache HIT for KEY: " + key);
        }
        return o;
    }

    public Object delete(String key) {
        return getCache().delete(NAMESPACE + key);
    }

    public MemcachedClient getCache() {
        MemcachedClient c = null;
        try {
            int i = (int) (Math.random() * 20);
            c = m[i];
        }catch (Exception e) {
            
        }
        return c;
    }

    private void configMemcache() {
        // Tell spy to use the Log4J
        Properties systemProperties = System.getProperties();
        systemProperties.put("net.spy.log.LoggerImpl", "net.spy.memcached.compat.log.Log4JLogger");
        System.setProperties(systemProperties);

    }
}
